import { applyMiddleware, legacy_createStore as createStore } from 'redux'

import { get, getJson, remove, set, setJson } from '@/utils/storage'

import logger from './logger'

export interface GlobalState {
  userInfo: {
    entityName: string
    entityNameAr: string
    entityId: string
    fullName: string
    fullNameAr: string
    mobile: string
    orgName: string
    token: string
    authorities: Array<{ authority: string }>
    avatar: string
    email: string
  }
  authorities: string[]
  token?: string
  websiteToken?: string
}

const initialState: GlobalState = {
  userInfo: getJson('userInfo'),
  token: get('userToken') as string,
  websiteToken: get('websiteToken') as string,
  authorities: getJson('authorities'),
}

function appReducer(state = initialState, action: any) {
  switch (action.type) {
    case 'update-userInfo': {
      const { userInfo = initialState.userInfo, authorities = [] } = action.payload
      setJson('userInfo', userInfo)
      setJson('authorities', authorities)
      return {
        ...state,
        authorities: authorities,
        userInfo,
      }
    }
    case 'update-authorities': {
      const { authorities = [] } = action.payload
      setJson('authorities', authorities)
      return {
        ...state,
        authorities: authorities,
      }
    }
    case 'update-token': {
      const { token } = action.payload
      set('userToken', token)
      return {
        ...state,
        token,
      }
    }
    case 'update-website-token': {
      const { token } = action.payload
      set('websiteToken', token)
      return {
        ...state,
        websiteToken: token,
      }
    }
    case 'reset': {
      remove('userToken')
      remove('websiteToken')
      remove('userInfo')
      remove('authorities')
      return {
        ...state,
        token: '',
        websiteToken: '',
        userInfo: { authorities: [], token: '' },
        authorities: [],
      }
    }
    default:
      return state
  }
}
const store = createStore(appReducer, applyMiddleware(logger))
export default store
